package com.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

@Component
public class ThirdFilter extends ZuulFilter {
    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        return 5;
    }

    @Override
    public boolean shouldFilter() {
        //获取请求上下文对象
        RequestContext ctx = RequestContext.getCurrentContext();
        return ctx.sendZuulResponse();
    }

    @Override
    public Object run() throws ZuulException {

//获取请求上下文对象
        RequestContext ctx = RequestContext.getCurrentContext();

        //获取请求对象
        HttpServletRequest request = ctx.getRequest();

        //获取请求参数
        String order = request.getParameter("order");

        System.out.println("filter 3 : " + order);
        System.out.println(ctx.get("msg"));

        //判断, key的值
        if (order != null && order.equals("2")){
            ctx.setSendZuulResponse(false);
            ctx.setResponseStatusCode(401);
            ctx.setResponseBody
                    ("{\"msg\":\"Access without pemission, pls login first.\"}");
        }

        ctx.set("msg", "你好, 老三!");

        return null;
    }
}
